package com.antis.olsl.magic.stave;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomView;
import com.antis.olsl.magic.R;
import com.antis.olsl.magic.adapter.StaveAdapter;
import com.antis.olsl.magic.databinding.ActivityStaveBinding;
import com.antis.olsl.magic.dialog.StaveDialog;
import com.antis.olsl.magic.response.StaveSummaryResp;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import timber.log.Timber;

/**
 * 五线谱
 *
 * @author hhh
 */
@Route(path = MagicRoutePath.ACTIVITY_STAVE)
public class StaveActivity extends BaseActivity<ActivityStaveBinding> implements OnChartValueSelectedListener, View.OnClickListener,
        StaveContract.View, ChooseDateDialog.ChooseDateListener, ChooseSalesroomView.ChooseSalesroomListener,
        ChooseSalesroomDialog.ChooseSalesroomListener {

    private ArrayList<Entry> values = new ArrayList<>();
    private ArrayList<Entry> values2 = new ArrayList<>();
    private ArrayList<Entry> values3 = new ArrayList<>();
    private ArrayList<Entry> values4 = new ArrayList<>();
    private ArrayList<Entry> values5 = new ArrayList<>();
    private ArrayList<String> xTexts = new ArrayList<>();
    private List<StaveSummaryResp.ContentBean.ShopListBean> mList = new ArrayList<>();

    private StaveDialog mDialog;
    private ChooseSalesroomDialog mSalesroomDialog;
    private ChooseDateDialog chooseDateDialog;

    private String salesRoomIds = "";
    private boolean chooseAllSalesroom = true;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();

    private StavePresenter mPresenter;
    private StaveAdapter mAdapter;
    private Date startDate;
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    @Override
    protected ActivityStaveBinding getViewBinding() {
        return ActivityStaveBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new StavePresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        initDate();
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroom();
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setChooseSalesroomListener(this);
        // setLineChartData();

        viewBinding.recyclerView.setNestedScrollingEnabled(false);

        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new StaveAdapter(R.layout.item_stave, mList);
        viewBinding.recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mList.size() > position) {
                    StaveSummaryResp.ContentBean.ShopListBean listBean = mList.get(position);
                    if (null != listBean) {
                        ARouter.getInstance().build(MagicRoutePath.ACTIVITY_STAVE_DETAIL)
                                .withSerializable("listBean", listBean)
                                .withString("startDate", simpleDateFormat.format(startDate))
                                .navigation();
                    }
                }
            }
        });

        viewBinding.rlChooseDate.setOnClickListener(this);
        viewBinding.llHead.imgTitleRight.setOnClickListener(this);
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        startDate = calendar.getTime();
        setDateText();
    }

    private void setDateText() {
        String date = textDateFormat.format(startDate);
        viewBinding.tvDate.setText(date);
    }

    @Override
    protected void initData() throws IllegalAccessException {
        loadData();
    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>(2);
        map.put("shopId", salesRoomIds);
        map.put("searchTime", dateFormat.format(startDate));
        mPresenter.staveSummary(map);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDialog) {
            mDialog.dismiss();
        }

        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }

        if (null != chooseDateDialog) {
            chooseDateDialog.dismiss();
        }

        if (null != mSalesroomDialog) {
            mSalesroomDialog.dismiss();
        }
    }

    private void initLineData() {
        xTexts.add("04-14");
        xTexts.add("04-15");
        xTexts.add("04-16");
        xTexts.add("04-17");
        xTexts.add("04-18");
        xTexts.add("04-19");

        values.add(new Entry(0, 350));
        values.add(new Entry(1, 410));
        values.add(new Entry(2, 402.1f));
        values.add(new Entry(3, 623.5f));
        values.add(new Entry(4, 596.4f));
        values.add(new Entry(5, 790.6f));

        values2.add(new Entry(0, 250.6f));
        values2.add(new Entry(1, 389.5f));
        values2.add(new Entry(2, 376.5f));
        values2.add(new Entry(3, 384));
        values2.add(new Entry(4, 500));
        values2.add(new Entry(5, 750));

        values3.add(new Entry(0, 250.6f));
        values3.add(new Entry(1, 397));
        values3.add(new Entry(2, 376.5f));
        values3.add(new Entry(3, 384));
        values3.add(new Entry(4, 500));
        values3.add(new Entry(5, 750));

        values4.add(new Entry(0, 300.6f));
        values4.add(new Entry(1, 207.5f));
        values4.add(new Entry(2, 376.5f));
        values4.add(new Entry(3, 231.5f));
        values4.add(new Entry(4, 420));
        values4.add(new Entry(5, 650));

        values5.add(new Entry(0, 300.6f));
        values5.add(new Entry(1, 207.5f));
        values5.add(new Entry(2, 376.5f));
        values5.add(new Entry(3, 195));
        values5.add(new Entry(4, 403));
        values5.add(new Entry(5, 650));
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        int iEntry = (int) e.getX();
        float valEntry1 = 0;
        if (values.size() >= iEntry) {
            valEntry1 = values.get(iEntry).getY();
        }
        float valEntry2 = 0;
        if (values2.size() >= iEntry) {
            valEntry2 = values2.get(iEntry).getY();
        }
        float valEntry3 = 0;
        if (values3.size() >= iEntry) {
            valEntry3 = values3.get(iEntry).getY();
        }
        float valEntry4 = 0;
        if (values4.size() >= iEntry) {
            valEntry4 = values4.get(iEntry).getY();
        }
        float valEntry5 = 0;
        if (values5.size() >= iEntry) {
            valEntry5 = values5.get(iEntry).getY();
        }
        Timber.tag("hhh").e("iEntry= " + iEntry + " ,valEntry1= " + valEntry1 + " ,valEntry2= "
                + valEntry2 + " ,valEntry3= " + valEntry3 + " ,valEntry4= " + valEntry4 + " ,valEntry5= " + valEntry5);

        StringBuilder stringProfitLoss = new StringBuilder();
        stringProfitLoss.append("盈亏  ");
        stringProfitLoss.append(valEntry1);
        viewBinding.textProfitLoss.setText(stringProfitLoss);

        StringBuilder stringActual = new StringBuilder();
        stringActual.append("实际  ");
        stringActual.append(valEntry2);
        viewBinding.textActual.setText(stringActual);

        StringBuilder stringTarget = new StringBuilder();
        stringTarget.append("目标  ");
        stringTarget.append(valEntry3);
        viewBinding.textTarget.setText(stringTarget);

        StringBuilder stringMom = new StringBuilder();
        stringMom.append("环比  ");
        stringMom.append(valEntry4);
        viewBinding.textMom.setText(stringMom);

        StringBuilder stringYoy = new StringBuilder();
        stringYoy.append("同比  ");
        stringYoy.append(valEntry5);
        viewBinding.textYoy.setText(stringYoy);
    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_chooseDate) {
            chooseDateDialog = new ChooseDateDialog(this, "选择时间", startDate, this, "startDate");
        } else if (id == R.id.img_titleRight) {
            showStaveDialog();
        }
    }

    private void showStaveDialog() {
        List<String> list = new ArrayList<>();
        list.add("1.统计表金额单位为万");
        list.add("2.顶部金额为累计实际销售金额");
        list.add("3.统计日期跨度最长为7天");
        list.add("4.长按图表，可查看日数据");
        mDialog = new StaveDialog(this, list);
        mDialog.show();
    }

    @Override
    public void getSalesroomInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        Timber.tag("hhh").e("getSalesroomInfoListSuccess resp= " + list.size());

        mSalesroomDialog = new ChooseSalesroomDialog(this, salesroomInfos, StaveActivity.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure");
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void staveSummarySuccess(StaveSummaryResp.ContentBean bean) {
        if (null != bean.dateList && bean.dateList.size() > 0) {
            xTexts.clear();
            xTexts.addAll(bean.dateList);
            values.clear();
            values2.clear();
            values3.clear();
            values4.clear();
            values5.clear();

            for (int i = 0; i < xTexts.size(); i++) {
                values.add(new Entry(i, bean.salePoLList.get(i)));
                values2.add(new Entry(i, bean.saleRealityList.get(i)));
                values3.add(new Entry(i, bean.saleTargetList.get(i)));
                values4.add(new Entry(i, bean.saleQoQList.get(i)));
                values5.add(new Entry(i, bean.saleYoYList.get(i)));
            }

            setLineChartData();
        }

        if (null != bean.shopList && bean.shopList.size() > 0) {
            mList.clear();
            mList.addAll(bean.shopList);
            mAdapter.setList(mList);

            StringBuilder storeNum = new StringBuilder();
            storeNum.append("共");
            storeNum.append(mList.size());
            storeNum.append("门店");
            viewBinding.textStoreNum.setText(storeNum);
        }
    }

    private void setLineChartData() {
        // initLineData();

        viewBinding.lineChart.setDrawGridBackground(false);
        viewBinding.lineChart.getDescription().setEnabled(false);
        viewBinding.lineChart.setDrawBorders(false);

        // mLineChart.getAxisLeft().setEnabled(false);
        viewBinding.lineChart.getAxisLeft().setDrawAxisLine(false);
        viewBinding.lineChart.getAxisRight().setDrawAxisLine(false);
        viewBinding.lineChart.getAxisRight().setEnabled(false);
        // mLineChart.getXAxis().setDrawAxisLine(false);
        // mLineChart.getAxisRight().setDrawGridLines(false);
        viewBinding.lineChart.getXAxis().setDrawAxisLine(false);
        viewBinding.lineChart.getXAxis().setDrawGridLines(false);

        viewBinding.lineChart.setOnChartValueSelectedListener(this);

        viewBinding.lineChart.getDescription().setEnabled(false);
        viewBinding.lineChart.getLegend().setEnabled(false);
        viewBinding.lineChart.setScaleXEnabled(false);
        viewBinding.lineChart.setScaleYEnabled(false);

        YAxis leftAxis = viewBinding.lineChart.getAxisLeft();
        // leftAxis.setAxisMaximum(800);
        // leftAxis.setAxisMinimum(0);
        leftAxis.setLabelCount(4);
        leftAxis.setGridLineWidth(1f);
        leftAxis.setGridColor(Color.parseColor("#e7e4e4"));
        leftAxis.setTextColor(Color.parseColor("#a3abb5"));
        leftAxis.setTextSize(10f);
        // leftAxis.enableGridDashedLine(10f, 10f, 0f);

        XAxis xAxis = viewBinding.lineChart.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setTextColor(Color.parseColor("#363e4b"));
        xAxis.setTextSize(10f);
        xAxis.setLabelCount(xTexts.size(), false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (value >= 0 && value < xTexts.size()) {
                    int index = (int) (value);
                    return (xTexts.get(index));
                }
                return "";
            }
        });

        LineDataSet lineDataSet = new LineDataSet(values, "1");
        LineDataSet lineDataSet2 = new LineDataSet(values2, "2");
        LineDataSet lineDataSet3 = new LineDataSet(values3, "3");
        LineDataSet lineDataSet4 = new LineDataSet(values4, "4");
        LineDataSet lineDataSet5 = new LineDataSet(values5, "5");

        setLineData(lineDataSet, "#F3504F");
        setLineData(lineDataSet2, "#ae55f2");
        setLineData(lineDataSet3, "#f3af11");
        setLineData(lineDataSet4, "#5aa4ef");
        setLineData(lineDataSet5, "#b2bac2");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();

        dataSets.add(lineDataSet);
        dataSets.add(lineDataSet2);
        dataSets.add(lineDataSet3);
        dataSets.add(lineDataSet4);
        dataSets.add(lineDataSet5);
        LineData data = new LineData(dataSets);
        viewBinding.lineChart.setData(data);

        viewBinding.lineChart.animateXY(1000, 1000);
    }

    private void setLineData(LineDataSet lineDataSet, String color) {
        lineDataSet.setColor(Color.parseColor(color));
        lineDataSet.setCircleColor(Color.parseColor(color));
        lineDataSet.setDrawValues(false);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSet.setLineWidth(2);
    }

    @Override
    public void staveSummaryFailure(String msg) {
        Timber.tag("hhh").e("staveSummaryFailure");
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void onChooseSalesroomListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        chooseAllSalesroom = isChooseAll;
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        if (selectedIndex == -1) {
            salesRoomIds = "";
        } else {
            salesRoomIds = filterIds();
        }
        loadData();
    }

    public String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {

            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if (chooseAllSalesroom) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if (chooseAllSalesroom) {
            name = "全部门店";
            chooseALL = true;
        }
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(infos);
        return ids;
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        try {
            startDate = textDateFormat.parse(year + "年" + month + "月" + day + "日");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        chooseDateDialog.dismiss();
        loadData();
        setDateText();
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroomInfoList();
        } else {
            mSalesroomDialog = new ChooseSalesroomDialog(this, salesroomInfos, StaveActivity.this);
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getSalesroomInfoList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }
}
